#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 30

void read_routine(int sock, char *buf);

void write_routine(int sock, char *buf);

int main(int argc, char *argv[])
{
    int sock;
    pid_t pid;
    char buf[BUF_SIZE];
    struct sockaddr_in serv_addr;

    sock = socket(AF_INET, SOCK_STREAM, 0);
    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = PF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons((uint16_t)atoi(argv[2]));

    connect(sock, (const struct sockaddr *)&serv_addr, sizeof(serv_addr));

    pid = fork();
    if(pid == 0) {
        write_routine(sock, buf);
    } else {
        read_routine(sock, buf);
    }
    close(sock);
    return 0;
}

void read_routine(int sock, char *buf)
{
    printf("读子进程\n");
    while(1) {
        int str_len = (int)read(sock, buf, BUF_SIZE);
        if(str_len == 0) {
            return;
        }
        buf[str_len]=0;
        printf("服务器传来的消息：%s", buf);
    }
}

void write_routine(int sock, char *buf)
{
    printf("写子进程\n");
    while(1) {
        fgets(buf, BUF_SIZE, stdin);
        if(!strcmp(buf, "q\n")) {
            shutdown(sock, SHUT_WR);
            return;
        }
        write(sock, buf, strlen(buf));
    }
}